package com.yunyilian8.www.jokeapp.activity;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;

import com.yunyilian8.www.jokeapp.R;
import com.yunyilian8.www.jokeapp.adapter.CustomViewPagerAdapter;
import com.yunyilian8.www.jokeapp.base.BaseFragmentActivity;
import com.yunyilian8.www.jokeapp.bean.AnyEventType;
import com.yunyilian8.www.jokeapp.fragment.HomeMyFragment;
import com.yunyilian8.www.jokeapp.fragment.HomeNull03Fragment;
import com.yunyilian8.www.jokeapp.fragment.HomeSmilingFaceFragment;
import com.yunyilian8.www.jokeapp.fragment.VideoPlayFragment;
import com.yunyilian8.www.jokeapp.listener.PhoChooerDialogListener;
import com.yunyilian8.www.jokeapp.utils.ActivityUtil;
import com.yunyilian8.www.jokeapp.utils.EventBusEvents;
import com.yunyilian8.www.jokeapp.utils.ToastUtil;
import com.yunyilian8.www.jokeapp.utils.UITools;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;


/*****************************************************
 * author:      wyb
 * email:       276698048@qq.com
 * date:        2017/2/9  16:07
 * description: 程序主页面
 *****************************************************/
public class HomeActivity extends BaseFragmentActivity implements CompoundButton.OnCheckedChangeListener {

    @InjectView(R.id.cvp_viewPager)
    ViewPager mViewPager;
    @InjectView(R.id.rbtn_01)
    RadioButton mRbtn01;
    @InjectView(R.id.rbtn_02)
    RadioButton mRbtn02;
    @InjectView(R.id.rbtn_03)
    RadioButton mRbtn03;
    @InjectView(R.id.rbtn_04)
    RadioButton mRbtn04;
    @InjectView(R.id.rg_layout)
    RadioGroup mRb;
    @InjectView(R.id.rl_bottom)
    RelativeLayout mRlBottom;
    private boolean mIsMenuOpened = false;
    private long mExitTime;
    private static final int PHOTO_REQUEST_CAREMA = 1;// 拍照
    private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择
    private static final int PHOTO_REQUEST_CUT = 3;// 结果
    /**
     * fragment管理器
     **/
    private FragmentManager mFragmentManager;
    /**
     * 用于填充viewPager的list数据
     **/
    private List<Fragment> mFragmentList = new ArrayList<>();
    //当前页卡
    private int mPage;
    private PhoChooerDialogListener mListener;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        ButterKnife.inject(this);
        EventBus.getDefault().register(this);
        //竖屏
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        initFragments();
        /**设置的监听**/
        setButtonListener();
    }

    public void onEventMainThread(AnyEventType event) {
        switch (event.getType()) {
            case EventBusEvents.NIGHT_MODE_ON:
                //夜间模式开始
                mRb.setBackgroundColor(getResources().getColor(R.color.color_646464_alpha));
                break;
            case EventBusEvents.NIGHT_MODE_OFF:
                //白天模式
                mRb.setBackgroundColor(getResources().getColor(R.color.color_white));
                break;
        }
    }


    /**
     * 设置的监听
     */
    private void setButtonListener() {
        //设置button的监听
        mRbtn01.setOnCheckedChangeListener(this);
        mRbtn02.setOnCheckedChangeListener(this);
        mRbtn03.setOnCheckedChangeListener(this);
        mRbtn04.setOnCheckedChangeListener(this);

        //设置viewPager的监听
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                switch (position) {
                    case 0:
                        //滑动到 笑话
                        mRbtn01.setChecked(true);

                        mRbtn02.setChecked(false);
                        mRbtn03.setChecked(false);
                        mRbtn04.setChecked(false);

                        mPage = 0;
                        //通知停止播放视频
                        EventBusEvents.EventBusChange(new AnyEventType(EventBusEvents.EVENT_VIDEO_STOP, null));
                        break;
                    case 1:
                        //滑动到 菜单2
                        mRbtn02.setChecked(true);

                        mRbtn01.setChecked(false);
                        mRbtn03.setChecked(false);
                        mRbtn04.setChecked(false);

                        mPage = 1;
                        //通知开始播放视频
                        EventBusEvents.EventBusChange(new AnyEventType(EventBusEvents.EVENT_VIDEO_START, null));
                        break;

                    case 2:
                        //滑动到 菜单3
                        mRbtn03.setChecked(true);

                        mRbtn01.setChecked(false);
                        mRbtn02.setChecked(false);
                        mRbtn04.setChecked(false);

                        mPage = 2;
                        //通知停止播放视频
                        EventBusEvents.EventBusChange(new AnyEventType(EventBusEvents.EVENT_VIDEO_STOP, null));
                        break;
                    case 3:
                        //滑动到 '我的'
                        mRbtn04.setChecked(true);

                        mRbtn01.setChecked(false);
                        mRbtn02.setChecked(false);
                        mRbtn03.setChecked(false);

                        mPage = 3;
                        //通知停止播放视频
                        EventBusEvents.EventBusChange(new AnyEventType(EventBusEvents.EVENT_VIDEO_STOP, null));
                        break;
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }


    /**
     * 初始化fragments
     */
    private void initFragments() {
        try {
            mFragmentManager = getSupportFragmentManager();


            /**'笑话'页面**/
            mFragmentList.add(new HomeSmilingFaceFragment());

            /**'菜单二'界面**/
            mFragmentList.add(new VideoPlayFragment());

            /**'菜单三'界面**/
            mFragmentList.add(new HomeNull03Fragment());

            /**'我的'界面**/
            mFragmentList.add(new HomeMyFragment());

            mViewPager.setOffscreenPageLimit(0);
            // mViewPager.setOnPageChangeListener(this);
            mViewPager.setAdapter(new CustomViewPagerAdapter(mFragmentList, mFragmentManager));
            mViewPager.setCurrentItem(0);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @OnClick({R.id.rbtn_01, R.id.rbtn_02, R.id.rbtn_03, R.id.rbtn_04})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rbtn_01:
                //点击了笑话
                mViewPager.setCurrentItem(0);

                mRbtn02.setChecked(false);
                mRbtn03.setChecked(false);
                mRbtn04.setChecked(false);

                mPage = 0;

                //设置屏幕不可以旋转
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
                break;
            case R.id.rbtn_02:
                //点击了菜单2
                mViewPager.setCurrentItem(1);

                mRbtn01.setChecked(false);
                mRbtn03.setChecked(false);
                mRbtn04.setChecked(false);

                mPage = 1;

                //设置屏幕可以旋转
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
                break;
            case R.id.rbtn_03:
                //点击了菜单3
                mViewPager.setCurrentItem(2);

                mRbtn01.setChecked(false);
                mRbtn02.setChecked(false);
                mRbtn04.setChecked(false);

                mPage = 2;

                //设置屏幕不可以旋转
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
                break;
            case R.id.rbtn_04:
                //点击了'我的'
                mViewPager.setCurrentItem(3);

                mRbtn01.setChecked(false);
                mRbtn02.setChecked(false);
                mRbtn03.setChecked(false);

                mPage = 3;

                //设置屏幕不可以旋转
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
                break;
        }
    }

    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
        if (isChecked) {
            compoundButton.setTextColor(getResources().getColor(R.color.cornflowerblue));
        } else {
            compoundButton.setTextColor(getResources().getColor(R.color.gray20));
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {

            if (mPage == 1 && ActivityUtil.isScreenChange(mCtx)) {
                //说明是横屏,应该先设置为竖屏
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                return true;
            }

            if (!mIsMenuOpened) {
                if ((System.currentTimeMillis() - mExitTime) > 2000) {
                    ToastUtil.showToast(mAppContext, "再按一次退出程序");
                    mExitTime = System.currentTimeMillis();
                } else {
                    finish();
                }
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 动态设置viewPager距离底部的距离(解决横竖屏切换底部RadioGroup显示的问题)
     */
    public void setBottomState(boolean b) {
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) mViewPager.getLayoutParams();
        if (b) {
            params.bottomMargin = UITools.dip2px(mCtx, 0);
            mViewPager.setLayoutParams(params);
            mRlBottom.setVisibility(View.GONE);
        } else {
            params.bottomMargin = UITools.dip2px(mCtx, 50);
            mViewPager.setLayoutParams(params);
            mRlBottom.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 以下设置video播放的生命周期
     */
    @Override
    public void onPause() {
        super.onPause();
        //通知停止播放视频
        EventBusEvents.EventBusChange(new AnyEventType(EventBusEvents.EVENT_VIDEO_STOP, null));
    }

    @Override
    public void onResume() {
        super.onResume();
        //通知开始播放视频
        EventBusEvents.EventBusChange(new AnyEventType(EventBusEvents.EVENT_VIDEO_START, null));
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //通知停止播放视频
        EventBusEvents.EventBusChange(new AnyEventType(EventBusEvents.EVENT_VIDEO_STOP, null));
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == PHOTO_REQUEST_GALLERY) {
            /**从相册返回的数据-还未处理**/
            mListener.firstAlbumReturn(requestCode, resultCode, data);
        } else if (requestCode == PHOTO_REQUEST_CAREMA) {
            /**从相机返回的数据-还未处理**/
            mListener.firstCameraReturn(requestCode, resultCode, data);
        } else if (requestCode == PHOTO_REQUEST_CUT) {
            /**从剪切图片返回的数据-已处理**/
            mListener.processed(requestCode, resultCode, data);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    public void setPhoChooerListener(PhoChooerDialogListener listener) {
        this.mListener = listener;
    }
}
